import React, { useCallback, useMemo, useState } from 'react';
import { View, Text, Image, Video } from '@tarojs/components';
import './index.less';
import classNames from 'classnames';
import { convertToArray } from '@/src/utils/commonFun';
import { secondsToTime } from '@/src/common/util/util';
import HighlightText from '../highLight';
import { netWorkErrorInfo } from '@/src/utils/constants';
import store from '@/src/store';
import Taro from '@tarojs/taro';
import { halfScreenJump } from '@/src/utils/halfScreen';
//文字+视频
export interface VedioItemProps {
  /** 取消按钮点击事件 */
  gotoDetail: (item: any, name: string) => void;
  handleSelect?: (item: any) => void;
  mine?: boolean;
  select?: boolean;
  edit?: boolean;
  data: any;
  home?: boolean;
}

export default function VedioItem({
  mine,
  edit,
  data,
  home,
  gotoDetail,
  handleSelect,
}: VedioItemProps) {
  const contentImage: any = convertToArray(data.contentImage);
  const vedioContainerClass = classNames(
    'home-vedio-container',
    `home-vedio-container-${edit}`
  );
  //跳转雪茄详情
  const gotoCigaDetail = (e: any, data: any) => {
    e.stopPropagation(); // 阻止冒泡
    e.preventDefault(); // 防止默认
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({
      url: `/subPagesWiki/cigaDetail/index?sku=${data.cigarSku}`,
    });
  };

  //跳转雪茄柜详情
  const gotoCigaCabinetDetail = (e: any, data: any) => {
    e.stopPropagation(); // 阻止冒泡
    e.preventDefault(); // 防止默认

    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (
      data.contentCigarCabinetVo &&
      data.contentCigarCabinetVo.productShopPath
    ) {
      halfScreenJump(data.contentCigarCabinetVo.productShopPath, {
        onFail: (err) => {
          //打开失败回调
          Taro.showToast({
            title: '暂无商品信息，请稍后再试',
            icon: 'none',
          });
        },
        onReturn: ({ reason, extraData }) => {
          //关闭半屏回调
          console.log('return reason:', reason, extraData);
        },
      });
    } else {
      Taro.showToast({ title: '暂无商品信息，请稍后再试', icon: 'none' });
    }
  };
  const getImageSrc = useMemo(() => {
    switch (data.userInfoVo && data.userInfoVo.tag) {
      case '品牌方':
        return require('../../assert/imgs/user/pinpai.png');
      case '大咖':
        return require('../../assert/imgs/user/daka.png');
      case '雪茄吧':
        return require('../../assert/imgs/user/xuejiaba.png');
      case '侍咖师':
        return require('../../assert/imgs/user/shikashi.png');
      default: // 包括 null 的情况
        return null;
    }
  }, [data.userInfoVo]);

  // 计算封面：优先使用 contentImage；没有则用兜底图
  const cover =
    (Array.isArray(contentImage) && contentImage[0]) ||
    (typeof contentImage === 'string' && contentImage) ||
    '';
  console.log(cover, data, 'data=======cover');

  // 1) 先尝试从 URL 推断（优先）
  const urlPortraitGuess = useMemo(() => {
    if (!cover) return null;
    // 匹配 ...w_600,h_800 或 ...h_800,w_600（顺序都支持）
    const wMatch = cover.match(/[?&]?(?:x-oss-process=[^&]*,)?w_(\d+)/i);
    const hMatch = cover.match(/[?&]?(?:x-oss-process=[^&]*,)?h_(\d+)/i);
    const w = wMatch ? Number(wMatch[1]) : 0;
    const h = hMatch ? Number(hMatch[1]) : 0;
    if (w > 0 && h > 0) return h > w; // true=竖屏
    return null; // 没法从 URL 判断
  }, [cover]);

  // 2) onLoad 兜底（仅在 url 推断失败时生效）
  const [loadPortrait, setLoadPortrait] = useState<boolean | null>(null);
  const handleImgLoad = useCallback(
    (e) => {
      if (urlPortraitGuess !== null) return; // URL 已判断就不再覆盖
      const { width, height } = e.detail || {};
      if (width && height) setLoadPortrait(height > width);
    },
    [urlPortraitGuess]
  );

  const isPortrait = (urlPortraitGuess ?? loadPortrait) === true;

  return (
    <View className={vedioContainerClass}>
      {/* 左侧选择框 */}
      {mine && edit && (
        <View className="home-vedio-left">
          <Image
            className="home-vedio-btn"
            onClick={() => handleSelect && handleSelect(data)}
            src={
              data.select
                ? 'https://file.linkcook.cn/image/wineMiniProgram/login/checked.png'
                : 'https://file.linkcook.cn/image/wineMiniProgram/login/unchecked.png'
            }
          />
        </View>
      )}
      {/* 右侧内容 */}
      <View className="home-vedio-right">
        {data && (
          <View>
            <View
              className="home-vedio-title clamp1"
              onClick={() => gotoDetail(data, 'vedio')}
            >
              <HighlightText text={data?.title}></HighlightText>
              {/* {home && (
                <Text className="home-article-title clamp1">{data.title}</Text>
              )} */}
            </View>
            {/* 标题 */}
            {!mine && (
              <View
                className="home-vedio-header home-common-list"
                onClick={() => gotoDetail(data, 'userCenter')}
              >
                <Image
                  className="protrait-icon"
                  src={data.userInfoVo && data.userInfoVo.ucAvatarUrl}
                  lazyLoad // 懒加载头像
                />
                <Text className="protrait-name">
                  {data.userInfoVo && data.userInfoVo.ucNickname}
                </Text>
                <Image
                  className="protrait-tag"
                  src={data && data.userInfoVo && getImageSrc}
                />
                {/* <Image className="brand-icon" src={} /> */}
                {/* <Text className="brand-name">
                  {data.contentCigarVo && data.contentCigarVo.contentCigarBrand}
                </Text> */}
              </View>
            )}
          </View>
        )}

        <View
          className="home-vedio-content"
          onClick={() => gotoDetail(data, 'vedio')}
        >
          {/* 列表中不再渲染 <Video> —— 统一使用封面图，彻底消除大量 Video 带来的内存/解码开销 */}
          <View className="thumb">
            <Image
              src={cover}
              className="home-vedio-bg"
              {...(isPortrait
                ? { mode: 'aspectFill' as const }
                : { mode: 'scaleToFill' })}
              onLoad={handleImgLoad}
              lazyLoad
            />
          </View>
          {/* 播放按钮 */}
          <View className="home-vedio-play"></View>
          {/* 总时长 */}
          <View className="home-vedio-time">
            {secondsToTime(data.contentVideoDuration)}
          </View>
        </View>

        <View className="home-vedio-brower">
          {data.auditStatus === 1 ? (
            <Text className="home-vedio-tag">审核中</Text>
          ) : (
            <Text className="home-vedio-brower-text">
              {data.view > 10000
                ? Math.floor(data.view / 10000) + '万+'
                : data.view}
              浏览
            </Text>
          )}

          {data.contentCigarCabinetVo &&
            data.contentCigarCabinetVo.contentCigarCabinetBrand !== null && (
              <View
                className="home-vedio-brower-name"
                onClick={(e) => gotoCigaCabinetDetail(e, data)}
              >
                <Text className="author">
                  {data.contentCigarCabinetVo &&
                    data.contentCigarCabinetVo.contentCigarCabinetBrand}{' '}
                  {data.contentCigarCabinetVo &&
                    data.contentCigarCabinetVo.contentCigarCabinetZh}
                </Text>
                {data.contentCigarCabinetVo &&
                  data.contentCigarCabinetVo.contentCigarCabinetBrand !==
                    null && (
                    <Image
                      className="arrow"
                      src="https://file.linkcook.cn/image/wineMiniProgram/home/arrow.png"
                      lazyLoad
                    />
                  )}
              </View>
            )}

          {data.contentCigarVo &&
            !(
              data.contentCigarCabinetVo &&
              data.contentCigarCabinetVo.contentCigarCabinetBrand
            ) &&
            data.contentCigarVo &&
            data.contentCigarVo.contentCigarZh !== null && (
              <View
                className="home-comment-brower-name"
                onClick={(e) => gotoCigaDetail(e, data.contentCigarVo)}
              >
                <Text className="author clamp1">
                  {data.contentCigarVo && data.contentCigarVo.contentCigarBrand}{' '}
                  {data.contentCigarVo && data.contentCigarVo.contentCigarZh}
                </Text>
                {data.contentCigarVo &&
                  data.contentCigarVo.contentCigarBrand !== null && (
                    <Image
                      className="arrow"
                      src="https://file.linkcook.cn/image/wineMiniProgram/home/arrow.png"
                      lazyLoad
                    />
                  )}
              </View>
            )}
        </View>
      </View>
    </View>
  );
}
